package com.mineoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mineoj.common.ErrorCode;
import com.mineoj.exception.BusinessException;
import com.mineoj.model.entity.NoticeRead;
import com.mineoj.model.entity.Notice;
import com.mineoj.model.entity.NoticeRead;
import com.mineoj.model.entity.User;
import com.mineoj.service.NoticeReadService;
import com.mineoj.mapper.NoticeReadMapper;
import com.mineoj.service.NoticeService;
import com.mineoj.service.NoticeReadService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
* @author 明月
* @description 针对表【notice_read(公告已读)】的数据库操作Service实现
* @createDate 2025-04-12 22:55:02
*/
@Service
public class NoticeReadServiceImpl extends ServiceImpl<NoticeReadMapper, NoticeRead>
    implements NoticeReadService{

    @Resource
    private NoticeService noticeService;

    /**
     * 已读
     *
     * @param noticeId
     * @param loginUser
     * @return
     */
    @Override
    public int doNoticeRead(long noticeId, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Notice notice = noticeService.getById(noticeId);
        if (notice == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已已读
        long userId = loginUser.getId();
        // 每个用户串行已读
        // 锁必须要包裹住事务方法
        NoticeReadService noticeReadService = (NoticeReadService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()) {
            return noticeReadService.doNoticeReadInner(userId, noticeId);
        }
    }

    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param noticeId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doNoticeReadInner(long userId, long noticeId) {
        NoticeRead noticeRead = new NoticeRead();
        noticeRead.setUserId(userId);
        noticeRead.setNoticeId(noticeId);
        QueryWrapper<NoticeRead> readQueryWrapper = new QueryWrapper<>(noticeRead);
        NoticeRead oldNoticeRead = this.getOne(readQueryWrapper);
        boolean result;
        // 已已读
        if (oldNoticeRead != null) {
            return 0;
        } else {
            // 未已读
            result = this.save(noticeRead);
            if (result) {
                // 已读数 + 1
                result = noticeService.update()
                        .eq("id", noticeId)
                        .setSql("readNum = readNum + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }

}




